package com.vpclub.controller;

import com.vpclub.bean.Department;
import com.vpclub.bean.Employee;
import com.vpclub.dao.DepartmentDao;
import com.vpclub.dao.EmployeeDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

/**
 * @author : leimingchao
 * @date Date : 2021年07月31日 22:19
 */
@Controller
public class EmployeeController {

    @Autowired
    private EmployeeDao employeeDao;
    @Autowired
    private DepartmentDao departmentDao;


    @RequestMapping(value = "/employees")
    public String getEmployees(Model model) {
        Collection<Employee> employees = employeeDao.getAll();
        model.addAttribute("employees",employees);
        return "list";
    }

    @RequestMapping(value = "/toAddPage")
    public String toAddPage(Model model) {
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        model.addAttribute("employee",new Employee());
        return "add";
    }

    /**
     * 保存员工
     * @param employee
     * @return
     */
    @RequestMapping(value = "/employee",method = RequestMethod.POST)
    public String addEmployee(Employee employee) {
        System.out.println("要添加的员工：" + employee);
        employeeDao.save(employee);
        return "redirect:/employees";
    }

    /**
     * 查询员工，来到修改页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/employee/{id}",method = RequestMethod.GET)
    public String getEmployee(@PathVariable(value = "id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("employee",employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("departments",departments);
        return "edit";
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.PUT)
    public String updateEmployee(Employee employee) {
        System.out.println("要修改的员工：" + employee);
        employeeDao.save(employee);
        return "redirect:/employees";
    }

    @ModelAttribute
    public void myModelAttribute(@RequestParam(value = "id", required = false) Integer id, Model model) {
        if (id != null) {
            Employee employee = employeeDao.get(id);
            model.addAttribute("employee",employee);
        }
        System.out.println("haha");
    }

    @RequestMapping(value = "/employee/{id}", method = RequestMethod.DELETE)
    public String deleteEmployee(@PathVariable(value = "id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/employees";
    }
}
